﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Sunboxsoft.Common;

namespace Sunboxsoft.WinForm
{
    public class ModuleManager
    {
        public static ModuleConfiguration[] Scan()
        {
            string configFilePath = string.Format("{0}\\configs\\module.json", AppDomain.CurrentDomain.BaseDirectory);
            Logger.InfoToTag("WinForm", string.Format("scan module config file:{0}", configFilePath));
            return Newtonsoft.Json.JsonConvert.DeserializeObject<ModuleConfiguration[]>(System.IO.File.ReadAllText(configFilePath));
        }

        public static IModule[] Load()
        {

            ModuleConfiguration[] moduleConfigurationList = Scan();
            IModule[] modules = new IModule[moduleConfigurationList.Length];

            for (int index = 0; index < moduleConfigurationList.Length; index++)
            {
                string assemblyFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, moduleConfigurationList[index].Assembly);

                Logger.InfoToTag("WinForm", string.Format("load assembly:{0}", assemblyFilePath));
                Assembly assembly = Assembly.LoadFile(assemblyFilePath);
                Type[] types = assembly.GetTypes();
                for (int typeIndex = 0; typeIndex < types.Length; typeIndex++)
                {
                    if (string.Equals(types[typeIndex].FullName, moduleConfigurationList[index].Type))
                    {
                        IModule module = assembly.CreateInstance(types[typeIndex].FullName) as IModule;
                        if (module != null)
                        {
                            modules[index] = module;
                        }
                        else
                        {
                            modules[index] = null;
                            System.Diagnostics.Debug.WriteLine(string.Format("create instance for type:{0},error", types[typeIndex].FullName));
                        }
                    }
                }
            }
            return modules;
        }
    }
}
